package pl.edu.pk.adcampaignfacebook.security;



import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException;
 
public class HashMd5 { 
 
    private static String convertToHex(byte[] data) { 
        StringBuilder buf = new StringBuilder();
        for (byte aData : data) {
            int halfbyte = (aData >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = aData & 0x0F;
            } while (two_halfs++ < 1);
        } 
        return buf.toString();
    } 
 
    private static byte[] messageDigest(byte[] data) {
        try {
        	MessageDigest md = MessageDigest.getInstance("MD5");
        	byte[] md5hash;
            md.update(data, 0, data.length);
            md5hash = md.digest();
            return md5hash;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
        return null;
    }
    public static String MD5(String text){ 
		try {
			byte[] md5hash = messageDigest(text.getBytes("iso-8859-1"));
			return convertToHex(md5hash);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return null;
    } 
    public static String MD5(byte[] photo){
    	byte [] md5hash = messageDigest(photo);
        return convertToHex(md5hash);
    }

}
